from datetime import timedelta
from datetime import datetime
from rest_framework import serializers
from datetime import datetime

from .models import Question, Answer, Tags, QuestionTag


class QuestionSerializer(serializers.ModelSerializer):
    """
    问答详情序列化器
    """

    question_username = serializers.SerializerMethodField(label="提问用户的名称")
    tags = serializers.SerializerMethodField(label="问题所属标签")

    class Meta:
        model = Question
        fields = ["id", "title", "content", "likes_count", "answer_count", "question_username", "tags", "create_time",
                  "update_time"]

    def get_question_username(self, obj):
        try:
            name = obj.user.username
        except Exception:
            name = None
        return name

    def get_tags(self, obj):
        # 用空的列表去接收相关标签的名称
        tag_name_list = list()
        try:
            tag_relate_list = obj.questiontag_set.all()
        except Exception:
            # 如果没有查询出来，则有可能是服务器错误，默认返回空字符串
            return ""

        for tag_relate in tag_relate_list:
            tag_name_list.append(tag_relate.tags.name)

        return tag_name_list

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        drop_dict = ["likes_count", "answer_count", "content", "title"]  # 自定义删除字段
        if self.context.get("flag"):
            for content in drop_dict:
                ret.pop(content)

        return ret


class AnswerSerializer(serializers.ModelSerializer):
    """
    回答序列化器
    """

    answer_username = serializers.SerializerMethodField(label="回答用户的名称")
    answer_time = serializers.SerializerMethodField(label="回答更新的时间")

    class Meta:
        model = Answer
        fields = ["id", "content", "likes_count", "answer_username", "answer_time"]

    def get_answer_username(self, obj):
        try:
            name = obj.user.username
        except Exception:
            name = None
        return name

    def get_answer_time(self, obj):
        create_time = datetime.strptime(obj.create_time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
        current_time = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
        gap_time = ((current_time - create_time) - timedelta(hours=8))
        hours = (gap_time.seconds) // 3600
        return hours


class LikeSerializer(serializers.Serializer):
    """
    问题点赞序列化器
    """
    answer_id = serializers.IntegerField(label="回答用户的id", min_value=1, required=False)
    qs_like = serializers.IntegerField(label="点赞次数")

    def validated_qs_like(self, value):
        # 问题点赞参数的校验
        if not value:
            raise serializers.ValidationError("获取点赞量参数错误")

        return value


class AnswerCommitSerializer(serializers.ModelSerializer):
    """回答提交序列化器"""

    class Meta:
        model = Answer
        fields = ["id", "content"]
        extra_kwargs = {
            "content": {
                "write_only": True
            },
            "id": {
                "read_only": True
            }
        }

    def validate(self, attrs):
        # 获取当前的用户，将用户对象放入到attrs中，方便后期调用create方法
        # 获取问题的pk并将问题的，将问题查询对象放入到attrs中，方便后期调用create方法
        user = self.context['request'].user
        if not user:
            raise serializers.ValidationError("无效的用户")

        question_id = self.context['question']
        if not question_id:
            raise serializers.ValidationError("问题不存在")

        try:
            question = Question.objects.get(id=question_id)
        except Exception:
            raise serializers.ValidationError("无效的问题")

        attrs['user'] = user
        attrs['question'] = question

        return attrs


class QuestionIndexSerializer(serializers.ModelSerializer):
    """
    问答首页序列化器
    """

    question_username = serializers.SerializerMethodField(label="提问用户", read_only=True)
    answer_username = serializers.SerializerMethodField(label="回答用户", read_only=True)

    class Meta:
        model = Question
        fields = ["id", "title", "hits", "likes_count", "answer_count", "create_time", "last_answer_time",
                  "question_username", "answer_username"]

    def get_answer_username(self, obj):
        try:
            username = obj.answer_set.order_by("-create_time")[0].user.username
        except Exception:
            username = None

        return username

    def get_question_username(self, obj):
        try:
            name = obj.user.username
        except Exception:
            name = None

        return name


class TagsSerializer(serializers.ModelSerializer):
    """
    所有标签序列化器
    """

    class Meta:
        model = Tags
        fields = ["id", "name", "concern"]


class QuestionSubmitSerializer(serializers.ModelSerializer):
    """
    问题提交序列化器

    {
        "title": "xxxx",
        "tags": "python,java,xxx",
        "content": "xxxxxxxxxx"
    }
    """

    # 用户信息可以通过context上下文获取
    # id只序列化用
    # 返回给前端的内容当前问题的id
    # tags按单个不切分的来做

    class Meta:
        model = Question
        fields = ["id", "title", "content"]
        extra_kwargs = {
            "id": {"read_only": True},
            "title": {"write_only": True},
            "content": {"write_only": True},
        }

    def validate(self, attrs):
        # 仅对当前的用户进行校验
        user = self.context['request'].user

        # 加入user字段后期存储用
        attrs['user'] = user
        attrs['last_answer_time'] = datetime.now()

        return attrs
